<template>
  <view class="page-container">
    <!-- 顶部导航栏 -->
    <view class="header" :class="{ 'scrolled': isHeaderScrolled }">
      <!-- 界面切换按钮 -->
      <view class="tab-buttons">
        <button :class="{ 'tab-active': currentTab === 'found' }" class="tab-button"
                @click="switchTab('found')">
          失物招领
        </button>
        <button :class="{ 'tab-active': currentTab === 'lost' }" class="tab-button" @click="switchTab('lost')">
          寻物启事
        </button>
      </view>

      <view class="search-bar">
        <uni-icons type="search" size="20" color="var(--color-text-secondary)" class="search-icon"></uni-icons>
        <input type="text" :placeholder="currentTab === 'found' ? '搜索失物...' : '搜索寻物...'" class="search-input"
               v-model="searchKeyword" @confirm="onSearch" @blur="onInputBlur" />
        <button class="search-btn" @click="onSearch">
          <text>搜索</text>
        </button>
      </view>

      <scroll-view scroll-x class="category-scroll">
        <view class="category-container">
          <button v-for="(category, index) in categories" :key="category.id"
                  :class="{ 'active': activeCategory === index }" class="category-btn"
                  @click="switchCategory(index)">
            {{ category.name }}
          </button>
        </view>
      </scroll-view>
    </view>

    <!-- 内容区域 -->
    <view class="content" :style="{'padding-top': headerHeight + 'rpx'}">
      <!-- 失物招领界面 -->
      <view class="tab-content" v-if="currentTab === 'found'"
            :class="{'fade-in': !isLoading && currentTab === 'found'}">
        <!-- 骨架屏加载状态 -->
        <view class="skeleton-container" v-if="isLoading && !foundItems.length">
          <view class="skeleton-item" v-for="i in 6" :key="i">
            <view class="skeleton-image"></view>
            <view class="skeleton-info">
              <view class="skeleton-title"></view>
              <view class="skeleton-meta"></view>
              <view class="skeleton-meta"></view>
              <view class="skeleton-desc"></view>
            </view>
          </view>
        </view>

        <!-- 失物卡片列表 - 带玻璃效果 -->
        <view class="item-grid" v-if="foundItems.length > 0 && !isLoading">
          <view v-for="item in foundItems" :key="item.id || item.foundId" class="item-card glass-effect"
                @click="goToDetail(item.id)" :class="{'loaded': imageStatus[`found-${item.id}`]}">
            <view class="item-image-container">
              <image :src="getFirstImageUrl(item.images)" mode="aspectFill" class="item-image"
                     @load="onImageLoad('found', item.id)" @error="onImageError('found', item.id)" />
              <view v-if="item.status" :class="['status-tag', `status-${item.status}`]">
                {{ getStatusText(item.status) }}
              </view>
            </view>

            <view class="item-info">
              <text class="item-title">{{ item.title || '未命名物品' }}</text>
              <view class="item-meta">
                <uni-icons type="location-filled" size="14"
                           color="var(--color-text-secondary)"></uni-icons>
                <text class="meta-text">{{ item.foundLocation || '未知地点' }}</text>
              </view>
              <view class="item-meta">
                <uni-icons type="clock-filled" size="14"
                           color="var(--color-text-secondary)"></uni-icons>
                <text class="meta-text category-text">{{ getCategoryName(item.categoryId) }}</text>
              </view>
              <view class="item-meta">
                <uni-icons type="time" size="14" color="var(--color-text-secondary)"></uni-icons>
                <text class="meta-text">{{ formatTime(item.foundTime) }}</text>
              </view>
              <text class="item-desc">{{ item.description || '暂无描述' }}</text>
            </view>
          </view>
        </view>

        <!-- 空状态 -->
        <view class="empty-state" v-else-if="!isLoading && !foundItems.length">
          <view class="empty-icon-container">
            <image src="/static/images/empty.png" mode="aspectFit" class="empty-icon"></image>
          </view>
          <text class="empty-text">暂无失物招领信息</text>
          <button class="refresh-btn" @click="loadInitialFoundItems">
            <uni-icons type="refresh" size="18" class="refresh-icon"></uni-icons>
            <text>刷新</text>
          </button>
        </view>

        <!-- 分页控制 -->
        <view class="pagination" v-if="totalFoundPages > 1 && !isLoading">
          <view class="pagination-info">
            <text>共 {{ totalFoundRecords }} 条失物记录</text>
          </view>
          <view class="pagination-controls">
            <button class="pagination-btn" :disabled="currentFoundPage === 1" @click="goToFoundPage(1)">
              <uni-icons type="arrowleft" size="16"></uni-icons>
              <text>首页</text>
            </button>

            <button class="pagination-btn" :disabled="currentFoundPage === 1"
                    @click="goToFoundPage(currentFoundPage - 1)">
              <uni-icons type="arrowleft" size="16" class="arrow-icon"></uni-icons>
            </button>

            <view class="page-numbers">
              <button v-for="page in visibleFoundPages" :key="page" class="page-number"
                      :class="{ 'active': page === currentFoundPage }" @click="goToFoundPage(page)">
                {{ page }}
              </button>
            </view>

            <button class="pagination-btn" :disabled="currentFoundPage === totalFoundPages"
                    @click="goToFoundPage(currentFoundPage + 1)">
              <uni-icons type="arrowright" size="16" class="arrow-icon"></uni-icons>
            </button>

            <button class="pagination-btn" :disabled="currentFoundPage === totalFoundPages"
                    @click="goToFoundPage(totalFoundPages)">
              <text>末页</text>
              <uni-icons type="arrowright" size="16"></uni-icons>
            </button>
          </view>
        </view>
      </view>

      <!-- 寻物启事界面 -->
      <view class="tab-content" v-if="currentTab === 'lost'"
            :class="{'fade-in': !isLoading && currentTab === 'lost'}">
        <!-- 骨架屏加载状态 -->
        <view class="skeleton-container" v-if="isLoading && !lostItems.length">
          <view class="skeleton-item" v-for="i in 6" :key="i">
            <view class="skeleton-image"></view>
            <view class="skeleton-info">
              <view class="skeleton-title"></view>
              <view class="skeleton-meta"></view>
              <view class="skeleton-meta"></view>
              <view class="skeleton-desc"></view>
            </view>
          </view>
        </view>

        <!-- 寻物卡片列表 - 带玻璃效果 -->
        <view class="item-grid" v-if="lostItems.length > 0 && !isLoading">
          <view v-for="item in lostItems" :key="item.id || item.lostId" class="item-card glass-effect"
                @click="goToLostDetail(item.id)" :class="{'loaded': imageStatus[`lost-${item.id}`]}">
            <view class="item-image-container">
              <image :src="getFirstImageUrl(item.images)" mode="aspectFill" class="item-image"
                     @load="onImageLoad('lost', item.id)" @error="onImageError('lost', item.id)" />
              <view v-if="item.status" :class="['status-tag', `status-${item.status}`]"
                    style="background-color: var(--color-warning);">
                {{ getStatusText(item.status) }}
              </view>
            </view>

            <view class="item-info">
              <text class="item-title">{{ item.title || '未命名物品' }}</text>
              <view class="item-meta">
                <uni-icons type="location-filled" size="14"
                           color="var(--color-text-secondary)"></uni-icons>
                <text class="meta-text">{{ item.lostLocation || '未知地点' }}</text>
              </view>
              <view class="item-meta">
                <uni-icons type="clock-filled" size="14"
                           color="var(--color-text-secondary)"></uni-icons>
                <text class="meta-text category-text">{{ getCategoryName(item.categoryId) }}</text>
              </view>
              <view class="item-meta">
                <uni-icons type="time" size="14" color="var(--color-text-secondary)"></uni-icons>
                <text class="meta-text">{{ formatTime(item.lostTime) }}</text>
              </view>
              <text class="item-desc">{{ item.description || '暂无描述' }}</text>
            </view>
          </view>
        </view>

        <!-- 空状态 -->
        <view class="empty-state" v-else-if="!isLoading && !lostItems.length">
          <view class="empty-icon-container">
            <image src="/static/images/empty.png" mode="aspectFit" class="empty-icon"></image>
          </view>
          <text class="empty-text">暂无寻物启事信息</text>
          <button class="refresh-btn" @click="loadInitialLostItems">
            <uni-icons type="refresh" size="18" class="refresh-icon"></uni-icons>
            <text>刷新</text>
          </button>
        </view>

        <!-- 分页控制 -->
        <view class="pagination" v-if="totalLostPages > 1 && !isLoading">
          <view class="pagination-info">
            <text>共 {{ totalLostRecords }} 条寻物记录</text>
          </view>
          <view class="pagination-controls">
            <button class="pagination-btn" :disabled="currentLostPage === 1" @click="goToLostPage(1)">
              <uni-icons type="arrowleft" size="16"></uni-icons>
              <text>首页</text>
            </button>

            <button class="pagination-btn" :disabled="currentLostPage === 1"
                    @click="goToLostPage(currentLostPage - 1)">
              <uni-icons type="arrowleft" size="16" class="arrow-icon"></uni-icons>
            </button>

            <view class="page-numbers">
              <button v-for="page in visibleLostPages" :key="page" class="page-number"
                      :class="{ 'active': page === currentLostPage }" @click="goToLostPage(page)">
                {{ page }}
              </button>
            </view>

            <button class="pagination-btn" :disabled="currentLostPage === totalLostPages"
                    @click="goToLostPage(currentLostPage + 1)">
              <uni-icons type="arrowright" size="16" class="arrow-icon"></uni-icons>
            </button>

            <button class="pagination-btn" :disabled="currentLostPage === totalLostPages"
                    @click="goToLostPage(totalLostPages)">
              <text>末页</text>
              <uni-icons type="arrowright" size="16"></uni-icons>
            </button>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { ref, onMounted, watch, computed, reactive, onUnmounted, nextTick, onScroll } from 'vue';
import { onReady, onShow } from '@dcloudio/uni-app';
import { useRoute } from 'vue-router';

// 基础配置
const baseUrl = 'http://172.20.10.2:8080/api';
const defaultImage = '/static/images/default.png';

// 分类数据
const categories = ref([
  { id: 0, name: '全部' },
  { id: 1, name: '证件' },
  { id: 2, name: '电子' },
  { id: 3, name: '书籍' },
  { id: 4, name: '衣物' },
  { id: 5, name: '钥匙' },
  { id: 6, name: '其他' }
]);
const activeCategory = ref(0);
//获取userId
const userId = uni.getStorageSync('userId')

// 界面状态
const currentTab = ref('found'); // 'found' 失物招领, 'lost' 寻物启事
const searchKeyword = ref('');
const filterParams = reactive({
  categoryId: 0,
  page: 1,
  pageSize: 10
});

// 失物招领数据
const foundItems = ref([] as any[]);
const totalFoundRecords = ref(0);
const totalFoundPages = ref(1);
const currentFoundPage = ref(1);
const visibleFoundPages = ref([1]);

// 寻物启事数据
const lostItems = ref([] as any[]);
const totalLostRecords = ref(0);
const totalLostPages = ref(1);
const currentLostPage = ref(1);
const visibleLostPages = ref([1]);

// 图片加载状态
const imageStatus = ref<Record<string, boolean>>({});

// 加载状态
const isFoundLoading = ref(false);
const isLostLoading = ref(false);
const isLoading = computed(() => isFoundLoading.value || isLostLoading.value);

// 布局相关
const isMobile = ref(false);
const headerHeight = ref(0); // 头部总高度
let resizeListener: any = null;
const isHeaderScrolled = ref(false); // 导航栏滚动状态
let scrollHandler: any = null;

// 生命周期 - 挂载
onMounted(() => {
  checkDeviceType();
  calculateHeaderHeight();
  loadInitialFoundItems();
  setupScrollListener(); // 设置滚动监听
});

// 生命周期 - 显示
onShow(() => {
  loadInitialFoundItems();
});

// 检查设备类型（移动端/PC端）
const checkDeviceType = () => {
  const windowInfo = uni.getWindowInfo();
  isMobile.value = windowInfo.screenWidth < 768;
  setupResizeListener();
};

// 计算头部高度
const calculateHeaderHeight = () => {
  const tabButtonsHeight = 80; // 增大后的tab按钮高度
  const searchBarHeight = 64; // 搜索栏高度
  const categoryScrollHeight = 56; // 分类滚动栏高度
  const padding = 24 + 24; // 顶部和底部padding
  headerHeight.value = tabButtonsHeight + searchBarHeight + categoryScrollHeight + padding;
};

// 设置窗口大小监听
const setupResizeListener = () => {
  if (resizeListener) {
    uni.offWindowResize(resizeListener);
    resizeListener = null;
  }

  resizeListener = (res: any) => {
    isMobile.value = res.screenWidth < 768;
    calculateHeaderHeight();
    updateVisiblePages();
  };

  uni.onWindowResize(resizeListener);
};

// 设置滚动监听
const setupScrollListener = () => {
  // 优化滚动事件处理，使用节流函数
  let lastScrollTop = 0;
  let timeoutId: any = null;

  scrollHandler = (e: any) => {
    const scrollTop = e.scrollTop || 0;
    const scrollDiff = scrollTop - lastScrollTop;
    lastScrollTop = scrollTop;

    // 清除之前的定时器
    if (timeoutId) {
      clearTimeout(timeoutId);
    }

    // 延迟处理滚动事件，优化性能
    timeoutId = setTimeout(() => {
      // 当滚动距离超过10px时，触发导航栏悬浮效果
      isHeaderScrolled.value = scrollTop > 10;
    }, 30);
  };

  uni.onPageScroll(scrollHandler);
};

// 加载初始失物招领数据
const loadInitialFoundItems = () => {
  filterParams.page = 1;
  fetchFoundItems();
};

// 加载初始寻物启事数据
const loadInitialLostItems = () => {
  filterParams.page = 1;
  fetchLostItems();
};

// 切换分类
const switchCategory = (index: number) => {
  activeCategory.value = index;
  filterParams.categoryId = categories.value[index].id;

  if (currentTab.value === 'found') {
    fetchFoundItems();
  } else {
    fetchLostItems();
  }
};

// 切换界面标签
const switchTab = (tab: string) => {
  if (currentTab.value === tab) return;

  currentTab.value = tab;

  if (tab === 'found') {
    if (foundItems.value.length === 0) {
      loadInitialFoundItems();
    }
  } else {
    if (lostItems.value.length === 0) {
      loadInitialLostItems();
    }
  }
};

// 失物招领分页跳转
const goToFoundPage = (page: number) => {
  if (page < 1 || page > totalFoundPages.value || page === currentFoundPage.value) return;
  filterParams.page = page;
  currentFoundPage.value = page;
  fetchFoundItems();
};

// 寻物启事分页跳转
const goToLostPage = (page: number) => {
  if (page < 1 || page > totalLostPages.value || page === currentLostPage.value) return;
  filterParams.page = page;
  currentLostPage.value = page;
  fetchLostItems();
};

// 搜索
const onSearch = () => {
  const keyword = searchKeyword.value.trim();
  filterParams.page = 1;

  if (keyword) {
    filterParams.keyword = keyword;
  } else {
    delete filterParams.keyword;
  }

  if (currentTab.value === 'found') {
    fetchFoundItems();
  } else {
    fetchLostItems();
  }
};

// 输入框失焦事件
const onInputBlur = () => {
  if (!searchKeyword.value.trim()) {
    // 输入框为空，刷新页面
    searchKeyword.value = '';
    delete filterParams.keyword;

    if (currentTab.value === 'found') {
      loadInitialFoundItems();
    } else {
      loadInitialLostItems();
    }
  }
};

// 时间格式化
const formatTime = (date: any): string => {
  if (!date) return '未知时间';

  let targetDate: Date;
  try {
    if (typeof date === 'string') {
      const isoDate = date.replace(/\+00:00$/, 'Z');
      targetDate = new Date(isoDate);
      if (isNaN(targetDate.getTime())) {
        throw new Error('无效的日期格式');
      }
    } else {
      targetDate = date;
    }

    const now = new Date();
    const diff = now.getTime() - targetDate.getTime();

    if (diff < 0) {
      return targetDate.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
      });
    }

    const minutes = Math.floor(diff / (1000 * 60));
    const hours = Math.floor(minutes / 60);
    const days = Math.floor(hours / 24);

    if (days > 7) {
      return targetDate.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
      });
    }

    return days > 0
        ? `${days}天前`
        : hours > 0
            ? `${hours}小时前`
            : `${minutes}分钟前`;
  } catch (error) {
    console.error('时间格式化失败:', error);
    return '时间格式错误';
  }
};

// 跳转失物详情
const goToDetail = (id: number) => {
  // 2. 增加物品浏览次数
  uni.request({
    url: `${baseUrl}/Views/add`,
    method: 'GET',
    data: {
      itemId: id,
      type: currentTab.value
    }
  });
  // 3. 记录个人浏览历史
  let browsingData = {
    userId: userId,
    itemId: id,
    itemType: currentTab.value
  }
  console.log(browsingData)
  uni.request({
    url: `${baseUrl}/browsingHistory/add`,
    method: 'POST',
    data: browsingData,
    header: {
      'Content-Type': 'application/json',
    }
  })
  uni.navigateTo({
    url: `/pages/item-detail/Founddetail?id=${id}`
  });
};

// 跳转寻物详情
const goToLostDetail = (id: number) => {
  // 2. 增加物品浏览次数
  uni.request({
    url: `${baseUrl}/Views/add`,
    method: 'GET',
    data: {
      itemId: id,
      type: currentTab.value
    }
  });
  // 3. 记录个人浏览历史
  let browsingData = {
    userId: userId,
    itemId: id,
    itemType: currentTab.value
  }
  console.log(browsingData)
  uni.request({
    url: `${baseUrl}/browsingHistory/add`,
    method: 'POST',
    data: browsingData,
    header: {
      'Content-Type': 'application/json',
    }
  })
  uni.navigateTo({
    url: `/pages/item-detail/Lostdetail?id=${id}`
  });
};

// 图片加载成功
const onImageLoad = (type: string, id: number) => {
  imageStatus.value[`${type}-${id}`] = true;
  console.log(`图片加载成功: ${type}-${id}`);
};

// 图片加载失败
const onImageError = (type: string, id: number) => {
  nextTick(() => {
    imageStatus.value[`${type}-${id}`] = true;
    console.error(`图片加载失败，ID: ${id}，尝试使用默认图片`);

    // 额外日志：打印当前图片URL用于调试
    if (type === 'found') {
      const item = foundItems.value.find(item => item.id === id);
      if (item && item.images && item.images.length > 0) {
        console.error(`失败URL: ${item.images[0].url}`);
      }
    } else {
      const item = lostItems.value.find(item => item.id === id);
      if (item && item.images && item.images.length > 0) {
        console.error(`失败URL: ${item.images[0].url}`);
      }
    }
  });
};

// 获取第一张图片URL
const getFirstImageUrl = (images: any[] | null): string => {
  // 1. 空值/非数组判断
  if (!images || !Array.isArray(images) || images.length === 0) {
    return defaultImage;
  }

  // 2. 遍历数组寻找有效图片对象
  for (const img of images) {
    // 3. 确保元素是对象且包含url属性
    if (typeof img === 'object' && img !== null && img.url) {
      let url = String(img.url).trim();

      // 4. 优化URL处理：支持多种路径格式
      if (url.startsWith('http')) {
        // 已有完整URL，直接返回
        return url;
      } else if (url.startsWith('/api/')) {
        // 移除接口前缀（如/api/）
        return url.replace('/api/', '');
      } else if (url.includes('D:/uploadsImages/')) {
        // 移除本地文件路径
        return url.replace('D:/uploadsImages/', 'uploadsImages/');
      } else {
        // 拼接基础URL
        return baseUrl.replace('/api', '') + url;
      }
    }
  }

  // 所有元素均无效时返回默认图片
  return defaultImage;
};

// 获取失物招领数据
const fetchFoundItems = () => {
  isFoundLoading.value = true;

  uni.request({
    url: `${baseUrl}/FoundItem/page`,
    method: 'GET',
    data: {
      categoryId: filterParams.categoryId,
      page: filterParams.page,
      pageSize: filterParams.pageSize,
      keyword: filterParams.keyword || ''
    },
    success: (res: any) => {
      const pageData = res.data.data || {};
      const records = pageData.list || [];

      totalFoundRecords.value = pageData.total || 0;
      totalFoundPages.value = pageData.pages || 1;
      currentFoundPage.value = pageData.pageNum || 1;

      // 初始化图片状态
      records.forEach(item => {
        imageStatus.value[`found-${item.id}`] = false;
      });

      foundItems.value = records.map(item => ({
        ...item,
        id: Number(item.foundId) || 0,
        title: item.title || '未命名物品',
        description: item.description || '暂无描述',
        foundLocation: item.foundLocation || '未知地点',
        foundTime: item.foundTime || '',
        status: item.status || 0,
        categoryId: item.categoryId || 0,
        contactWay: item.contactWay || '暂无联系方式',
        images: item.images ? item.images.map(img => ({ url: img.url || '' })) : []
      }));

      console.log(`失物招领数据加载: ${foundItems.value.length}/${totalFoundRecords.value}`);
    },
    fail: (err: any) => {
      console.error('失物招领请求失败:', err);
      uni.showToast({ title: '网络错误，请稍后再试', icon: 'none' });
    },
    complete: () => {
      isFoundLoading.value = false;
      updateFoundVisiblePages();
    }
  });
};

// 获取寻物启事数据
const fetchLostItems = () => {
  isLostLoading.value = true;

  uni.request({
    url: `${baseUrl}/LostItem/page`,
    method: 'GET',
    data: {
      categoryId: filterParams.categoryId,
      page: filterParams.page,
      pageSize: filterParams.pageSize,
      keyword: filterParams.keyword || ''
    },
    success: (res: any) => {
      const pageData = res.data.data || {};
      const records = pageData.list || [];

      totalLostRecords.value = pageData.total || 0;
      totalLostPages.value = pageData.pages || 1;
      currentLostPage.value = pageData.pageNum || 1;

      // 初始化图片状态
      records.forEach(item => {
        imageStatus.value[`lost-${item.id}`] = false;
      });

      lostItems.value = records.map(item => ({
        ...item,
        id: Number(item.lostId) || 0,
        title: item.title || '未命名物品',
        description: item.description || '暂无描述',
        lostLocation: item.lostLocation || '未知地点',
        lostTime: item.lostTime || '',
        status: item.status || 0,
        categoryId: item.categoryId || 0,
        contactWay: item.contactWay || '暂无联系方式',
        images: item.images ? item.images.map(img => ({ url: img.url || '' })) : []
      }));

      console.log(`寻物启事数据加载: ${lostItems.value.length}/${totalLostRecords.value}`);
    },
    fail: (err: any) => {
      console.error('寻物启事请求失败:', err);
      uni.showToast({ title: '网络错误，请稍后再试', icon: 'none' });
    },
    complete: () => {
      isLostLoading.value = false;
      updateLostVisiblePages();
    }
  });
};

// 更新失物招领可见页码
const updateFoundVisiblePages = () => {
  const visiblePageCount = isMobile.value ? 3 : 5;
  let startPage = Math.max(1, currentFoundPage.value - Math.floor(visiblePageCount / 2));
  let endPage = startPage + visiblePageCount - 1;

  endPage = Math.min(endPage, totalFoundPages.value || 1);
  startPage = Math.max(1, endPage - visiblePageCount + 1);

  visibleFoundPages.value = Array.from({ length: endPage - startPage + 1 }, (_, i) => startPage + i);
};

// 更新寻物启事可见页码
const updateLostVisiblePages = () => {
  const visiblePageCount = isMobile.value ? 3 : 5;
  let startPage = Math.max(1, currentLostPage.value - Math.floor(visiblePageCount / 2));
  let endPage = startPage + visiblePageCount - 1;

  endPage = Math.min(endPage, totalLostPages.value || 1);
  startPage = Math.max(1, endPage - visiblePageCount + 1);

  visibleLostPages.value = Array.from({ length: endPage - startPage + 1 }, (_, i) => startPage + i);
};

// 更新所有可见页码
const updateVisiblePages = () => {
  if (currentTab.value === 'found') {
    updateFoundVisiblePages();
  } else {
    updateLostVisiblePages();
  }
};

// 获取状态文本
const getStatusText = (status: number): string => {
  const statusMap: Record<number, string> = {
    1: '已找到',
    2: '待领取',
    3: '处理中',
    4: '等待确认',
    5: '已过期'
  };
  return statusMap[status] || `状态${status}`;
};

// 获取分类名称
const getCategoryName = (categoryId: number): string => {
  const category = categories.value.find(cat => cat.id === categoryId);
  return category ? category.name : '未知分类';
};

// 监听设备类型或标签变化
watch([isMobile, currentTab], () => {
  updateVisiblePages();
});

// 生命周期 - 卸载
onUnmounted(() => {
  if (resizeListener) {
    uni.offWindowResize(resizeListener);
    resizeListener = null;
  }
  if (scrollHandler) {
    uni.offPageScroll(scrollHandler);
    scrollHandler = null;
  }
});
</script>

<style scoped>
page {
  height: 100%;
  background-color: var(--color-bg-light);
}

:root {
  --color-primary: #165DFF;        /* 主蓝色 - 深蓝基调 */
  --color-primary-light: rgba(22, 93, 255, 0.1);   /* 浅蓝色背景 - 用于卡片间隙 */
  --color-primary-dark: #0D47A1;    /* 深蓝色 */
  --color-secondary: #36CBCB;      /* 辅助色 - 青色 */
  --color-text-primary: #1D2129;    /* 主文本色 */
  --color-text-secondary: #4E5969;  /* 次要文本色 */
  --color-text-tertiary: #86909C;   /* 第三级文本色 */
  --color-bg-light: #F7F8FA;        /* 背景浅色 */
  --color-bg-white: #FFFFFF;        /* 白色背景 */
  --color-border: #E5E6EB;          /* 边框色 */
  --color-status-found: #52C41A;     /* 已找到状态色 - 绿色 */
  --color-status-lost: #FAAD14;      /* 寻物中状态色 - 黄色 */
  --color-status-expired: #F5222D;   /* 已过期状态色 - 红色 */
  --color-warning: #FAAD14;          /* 警告色 */
  --color-pink: #FF6B9B;             /* 粉色主题色 */
  --glass-bg: rgba(255, 255, 255, 0.85); /* 优化的玻璃态背景，提高透明度 */
  --glass-border: rgba(255, 255, 255, 0.4); /* 优化的玻璃态边框 */
  --glass-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.1); /* 优化的玻璃态阴影，降低不透明度 */
  --header-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.12); /* 导航栏悬浮阴影 */

  --font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
  --font-size-xs: 10px;
  --font-size-sm: 12px;
  --font-size-md: 14px;
  --font-size-lg: 16px;
  --font-size-xl: 18px;

  --spacing-xs: 6rpx;
  --spacing-sm: 12rpx;
  --spacing-md: 8rpx;
  --spacing-lg: 24rpx; /* 卡片间距增大 */
  --spacing-xl: 36rpx;
  --spacing-xxl: 48rpx;

  --border-radius-sm: 3rpx;
  --border-radius-md: 16rpx;         /* 增大圆角为16rpx */
  --border-radius-lg: 24rpx;
  --border-radius-full: 9999rpx;

  --shadow-sm: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);        /* 调整阴影以匹配大圆角 */
  --shadow-md: 0 6rpx 16rpx rgba(0, 0, 0, 0.1);       /* 中等阴影 */
  --shadow-lg: 0 10rpx 24rpx rgba(22, 93, 255, 0.15);   /* 蓝色悬浮阴影 */
  --shadow-hover: 0 16rpx 36rpx rgba(22, 93, 255, 0.2); /* 悬停增强阴影 */
}

view, text, button, input {
  box-sizing: border-box;
  font-family: var(--font-family);
}

button {
  border: none;
  background: none;
  padding: 0;
  margin: 0;
  font-size: inherit;
  color: inherit;
  cursor: pointer;
}

.page-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  background-color: var(--color-bg-light);
}

.header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 100;
  background-color: var(--color-bg-white);
  padding: var(--spacing-md) var(--spacing-lg);
  box-shadow: var(--shadow-sm);
  transition: all 0.3s ease;
}

.header.scrolled {
  padding: var(--spacing-sm) var(--spacing-md);
  box-shadow: var(--header-shadow); /* 滚动时增强阴影 */
  background-color: rgba(255, 255, 255, 0.95); /* 半透明背景 */
  backdrop-filter: blur(10rpx); /* 背景模糊 */
}

.tab-buttons {
  display: flex;
  justify-content: center;
  margin-bottom: var(--spacing-xs);
  border-bottom: 1rpx solid var(--color-border);
  padding-bottom: var(--spacing-xs);
}

.tab-button {
  padding: 0 calc(var(--spacing-md) * 2); /* 按钮内边距乘以2 */
  font-size: var(--font-size-lg); /* 增大字体 */
  height: 80rpx; /* 按钮高度增加 */
  line-height: 80rpx; /* 行高增加 */
  color: var(--color-text-secondary);
  position: relative;
  transition: all 0.2s ease;
  margin: 0 var(--spacing-md); /* 按钮间距乘以2 */
}

.tab-button.tab-active {
  color: var(--color-primary);
  font-weight: 500;
}

.tab-button.tab-active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 48rpx;
  height: 3rpx;
  background-color: var(--color-primary);
  border-radius: 1rpx;
}

.search-bar {
  display: flex;
  align-items: center;
  margin-bottom: var(--spacing-md);
  background-color: var(--color-primary-light);
  border-radius: var(--border-radius-lg);
  padding: 0 var(--spacing-md);
  height: 64rpx;
  transition: all 0.3s ease;
}

.header.scrolled .search-bar {
  height: 56rpx; /* 滚动时搜索栏高度减小 */
}

.search-bar:focus-within {
  box-shadow: 0 0 0 2rpx var(--color-primary-light);
}

.search-icon {
  margin-right: var(--spacing-xs);
}

.search-input {
  flex: 1;
  height: 100%;
  font-size: var(--font-size-md);
  color: var(--color-text-primary);
  background-color: transparent;
  border: none;
  outline: none;
}

.search-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  min-width: 80rpx;
  height: 44rpx;
  margin-left: var(--spacing-md);
  background-color: var(--color-primary);
  color: var(--color-bg-white);
  border-radius: var(--border-radius-lg);
  font-size: var(--font-size-md);
  transition: all 0.2s ease;
  box-shadow: var(--shadow-sm);
}

.search-btn:active {
  background-color: var(--color-primary-dark);
  transform: scale(0.98);
  box-shadow: var(--shadow-md);
}

.category-scroll {
  white-space: nowrap;
  width: 100%;
  height: 56rpx;
  overflow-x: auto;
  -webkit-overflow-scrolling: touch;
  padding-bottom: var(--spacing-xs);
}

.header.scrolled .category-scroll {
  height: 48rpx; /* 滚动时分类栏高度减小 */
}

.category-container {
  display: inline-flex;
}

.category-btn {
  display: inline-block;
  padding: 0 var(--spacing-md);
  height: 48rpx;
  line-height: 48rpx;
  margin-right: var(--spacing-sm);
  background-color: #f3f4f6;
  color: var(--color-text-secondary);
  border-radius: 24rpx; /* 分类按钮圆角增大 */
  font-size: var(--font-size-sm);
  transition: all 0.2s ease;
  box-shadow: var(--shadow-sm);
}

.category-btn.active {
  background-color: var(--color-primary);
  color: var(--color-bg-white);
  box-shadow: 0 4rpx 12rpx rgba(22, 93, 255, 0.25);
}

.category-btn:not(.active):hover {
  background-color: #e5e7eb;
}

.content {
  flex: 1;
  padding: 0 var(--spacing-lg) 120rpx;
  max-width: 1200rpx;
  margin: 0 auto;
  width: 100%;
  box-sizing: border-box;
  transition: all 0.3s ease;
}

.tab-content {
  animation: fadeIn 0.3s ease;
  display: flex;
  flex-direction: column;
  align-items: center;
  min-height: 100%;
  width: 100%; /* 确保内容区域占满宽度 */
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(10rpx); }
  to { opacity: 1; transform: translateY(0); }
}

.skeleton-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(calc(50% - 12rpx), 1fr)); /* 优化骨架屏布局 */
  gap: var(--spacing-lg);
  width: 100%;
}

.skeleton-item {
  background-color: var(--color-bg-white);
  border-radius: var(--border-radius-md); /* 骨架屏卡片大圆角 */
  overflow: hidden;
  box-shadow: var(--shadow-sm);
  animation: fadeIn 0.5s ease-in-out;
}

.skeleton-image {
  width: 100%;
  height: 300rpx;
  background-color: #f3f4f6;
  background: linear-gradient(90deg, #f3f4f6 25%, #e5e7eb 50%, #f3f4f6 75%);
  background-size: 200% 100%;
  animation: loading 1.5s infinite;
  border-radius: var(--border-radius-md) var(--border-radius-md) 0 0; /* 图片区域大圆角 */
}

.skeleton-info {
  padding: var(--spacing-md);
}

.skeleton-title {
  width: 80%;
  height: 32rpx;
  background-color: #f3f4f6;
  background: linear-gradient(90deg, #f3f4f6 25%, #e5e7eb 50%, #f3f4f6 75%);
  background-size: 200% 100%;
  animation: loading 1.5s infinite;
  border-radius: 4rpx;
  margin-bottom: var(--spacing-xs);
}

.skeleton-meta {
  width: 60%;
  height: 28rpx;
  background-color: #f3f4f6;
  background: linear-gradient(90deg, #f3f4f6 25%, #e5e7eb 50%, #f3f4f6 75%);
  background-size: 200% 100%;
  animation: loading 1.5s infinite;
  border-radius: 4rpx;
  margin-bottom: var(--spacing-xs);
}

.skeleton-desc {
  width: 90%;
  height: 28rpx;
  background-color: #f3f4f6;
  background: linear-gradient(90deg, #f3f4f6 25%, #e5e7eb 50%, #f3f4f6 75%);
  background-size: 200% 100%;
  animation: loading 1.5s infinite;
  border-radius: 4rpx;
}

@keyframes loading {
  0% { background-position: 200% 0; }
  100% { background-position: -200% 0; }
}

.item-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(calc(50% - 12rpx), 1fr)); /* 优化卡片布局，确保宽度正确 */
  gap: var(--spacing-md); /* 调整间距为固定值，避免计算误差 */
  background-color: var(--color-primary-light);
  padding: var(--spacing-md);
  width: 100%;
  margin: 0; /* 移除多余边距 */
  padding-top: 0; /* 移除多余内边距 */
}

.item-card {
  background: var(--glass-bg);
  backdrop-filter: blur(10rpx); /* 背景模糊 */
  -webkit-backdrop-filter: blur(10rpx);
  border: 1rpx solid var(--glass-border); /* 半透明边框 */
  box-shadow: var(--glass-shadow); /* 特殊阴影 */
  border-radius: var(--border-radius-lg); /* 玻璃态卡片大圆角 */
  border-bottom: 4rpx solid var(--color-pink); /* 粉色底部边框 */
  width: 100%; /* 确保卡片占满列宽 */
  overflow: hidden;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1); /* 平滑过渡 */
  opacity: 0;
  transform: translateY(20rpx);
  animation: fadeIn 0.5s ease forwards;
  will-change: transform, box-shadow;
}

.item-card:hover {
  transform: translateY(-12rpx);       /* 上浮距离增大 */
  box-shadow: 0 16rpx 36rpx rgba(22, 93, 255, 0.25); /* 增强玻璃态阴影 */
  z-index: 10;                        /* 提升层级 */
  border-color: rgba(22, 93, 255, 0.5); /* 边框变为半透明蓝色 */
}

.item-card.loaded {
  animation: fadeInLoaded 0.5s ease forwards;
}

@keyframes fadeIn {
  to { opacity: 1; transform: translateY(0); }
}

@keyframes fadeInLoaded {
  0% { opacity: 0; transform: translateY(10rpx); }
  100% { opacity: 1; transform: translateY(0); }
}

.item-image-container {
  position: relative;
  width: 100%;
  height: 300rpx;
  overflow: hidden;
}

.item-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.5s ease, opacity 0.3s ease;
}

.item-image.loaded {
  opacity: 1;
}

.item-image-container:hover .item-image {
  transform: scale(1.08);             /* 图片缩放比例增大 */
}

.status-tag {
  position: absolute;
  top: var(--spacing-xs);
  right: var(--spacing-xs);
  padding: 4rpx 12rpx;
  background-color: var(--color-status-found);
  color: var(--color-bg-white);
  border-radius: 16rpx;
  font-size: var(--font-size-xs);
  box-shadow: 0 2rpx 8rpx rgba(16, 185, 129, 0.3);
  display: flex;
  align-items: center;
  z-index: 1;
}

.status-tag.status-1 { background-color: #52C41A; }
.status-tag.status-2 { background-color: var(--color-primary); } /* 待领取状态使用主蓝色 */
.status-tag.status-3 { background-color: var(--color-warning); }
.status-tag.status-4 { background-color: #6366f1; }
.status-tag.status-5 { background-color: #F5222D; }

.status-tag::before {
  content: '';
  display: inline-block;
  width: 6rpx;
  height: 6rpx;
  border-radius: 50%;
  background-color: white;
  margin-right: 3rpx;
}

.item-info {
  padding: var(--spacing-md);
  background-color: rgba(255, 255, 255, 0.5); /* 半透明背景，增强玻璃态效果 */
}

.item-title {
  display: block;
  font-size: var(--font-size-lg);
  font-weight: 600;
  color: var(--color-text-primary);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  margin-bottom: var(--spacing-sm);
}

.item-meta {
  display: flex;
  align-items: center;
  margin-top: var(--spacing-xs);
  font-size: var(--font-size-sm);
  color: var(--color-text-secondary);
}

.category-text {
  color: var(--color-primary);
  font-weight: 500;
}

.meta-text {
  margin-left: var(--spacing-xs);
}

.item-desc {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  margin-top: var(--spacing-sm);
  font-size: var(--font-size-sm);
  color: var(--color-text-tertiary);
  line-height: 1.4;
}

.empty-state {
  text-align: center;
  padding: 150rpx 0;
  color: var(--color-text-tertiary);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 500rpx;
  width: 100%;
}

.empty-icon-container {
  width: 200rpx;
  height: 200rpx;
  margin-bottom: var(--spacing-md);
  opacity: 0.7;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: var(--color-primary-light);
  border-radius: var(--border-radius-lg); /* 空状态容器大圆角 */
}

.empty-icon {
  width: 120rpx;
  height: 120rpx;
}

.empty-text {
  font-size: var(--font-size-lg);
  margin-bottom: var(--spacing-md);
  color: var(--color-text-secondary);
}

.refresh-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 12rpx 32rpx;
  background-color: var(--color-primary);
  color: var(--color-bg-white);
  border-radius: var(--border-radius-lg); /* 刷新按钮大圆角 */
  font-size: var(--font-size-md);
  transition: all 0.2s ease;
  box-shadow: var(--shadow-sm);
}

.refresh-btn:active {
  background-color: var(--color-primary-dark);
  transform: scale(0.98);
  box-shadow: var(--shadow-md);
}

.pagination {
  margin-top: var(--spacing-xl);
  text-align: center;
  width: 100%;
}

.pagination-info {
  margin-bottom: var(--spacing-md);
  font-size: var(--font-size-sm);
  color: var(--color-text-tertiary);
}

.pagination-controls {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-wrap: wrap;
  gap: var(--spacing-sm);
}

.pagination-btn {
  min-width: 72rpx;
  height: 56rpx;
  line-height: 56rpx;
  padding: 0 var(--spacing-md);
  background-color: var(--color-bg-white);
  color: var(--color-text-secondary);
  border-radius: var(--border-radius-md); /* 分页按钮圆角 */
  font-size: var(--font-size-sm);
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1rpx solid var(--color-border);
  transition: all 0.2s ease;
  box-shadow: var(--shadow-sm);
}

.pagination-btn:disabled {
  background-color: #f9fafb;
  color: #d1d5db;
  cursor: not-allowed;
  border-color: #e5e7eb;
  box-shadow: none;
}

.pagination-btn:not(:disabled):active {
  background-color: #f3f4f6;
  transform: translateY(1rpx);
}

.page-numbers {
  display: flex;
  align-items: center;
  gap: var(--spacing-sm);
}

.page-number {
  width: 56rpx;
  height: 56rpx;
  line-height: 56rpx;
  background-color: var(--color-bg-white);
  color: var(--color-text-secondary);
  border-radius: 50%; /* 页码按钮圆形圆角 */
  font-size: var(--font-size-sm);
  text-align: center;
  border: 1rpx solid var(--color-border);
  transition: all 0.2s ease;
  box-shadow: var(--shadow-sm);
}

.page-number.active {
  background-color: var(--color-primary);
  color: var(--color-bg-white);
  border-color: var(--color-primary);
  box-shadow: 0 4rpx 12rpx rgba(22, 93, 255, 0.25);
}

.page-number:not(.active):hover {
  background-color: #f3f4f6;
}

.arrow-icon {
  margin: 0 var(--spacing-xs);
}

/* 响应式适配 */
@media (max-width: 768rpx) {
  .content {
    padding: 0 var(--spacing-md) 100rpx;
  }

  .item-grid {
    grid-template-columns: 1fr; /* 移动端单列布局 */
    gap: var(--spacing-lg);
  }

  .skeleton-container {
    grid-template-columns: 1fr; /* 移动端骨架屏单列布局 */
  }

  .pagination-controls {
    gap: var(--spacing-xs);
  }

  .pagination-btn {
    min-width: 60rpx;
    height: 48rpx;
    padding: 0 var(--spacing-xs);
    font-size: var(--font-size-xs);
  }

  .page-number {
    width: 48rpx;
    height: 48rpx;
    font-size: var(--font-size-xs);
  }

  .tab-button {
    padding: 0 var(--spacing-sm);
    font-size: var(--font-size-xs);
    height: 32rpx;
    line-height: 32rpx;
  }

  .search-bar {
    height: 56rpx;
  }

  .search-btn {
    min-width: 70rpx;
    height: 36rpx;
    font-size: var(--font-size-xs);
  }

  .category-btn {
    padding: 0 var(--spacing-sm);
    height: 40rpx;
    line-height: 40rpx;
    font-size: var(--font-size-xs);
  }
}
</style>